<?php

namespace app\admin\controller\zhongzhuan\fenpei;

use app\common\controller\Backend;
use think\db\exception\BindParamException;
use think\db\exception\DataNotFoundException;
use think\db\exception\ModelNotFoundException;
use think\exception\DbException;
use think\exception\PDOException;
use think\exception\ValidateException;
use think\Db;
use fast\Tree;


/**
 * 
 *
 * @icon fa fa-circle-o
 */
class Feiyuassignkehudetail extends Backend
{

    /**
     * Assignkehudetail模型对象
     * @var \app\admin\model\zhongzhuan\fenpei\Assignkehudetail
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\zhongzhuan\fenpei\Feiyuassignkehudetail;

    }



    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */

     /**
     * 查看
     */
    /**
     * 查看
     */
    public function index()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        $ids = $this->request->param('ids',1);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            
            $today_start_time = strtotime("today");
            $assign_id = db('ec_assign_feiyu_kehu')->where(['status'=>['<>',2]])->order('id desc')->value('id');
            if(empty($assign_id)){
                $result = array("total" => 0, "rows" => []);
                return json($result);
                exit;
            }
            
            
            list($where1, $sort, $order, $offset, $limit) = $this->buildparams();

            
            $request_data = $this->request->param();     
            $where_map = Null;
            if(!empty($request_data['deptId'])){
                $where_map['deptId'] = array('in',$request_data['deptId']);               
            }
            
            
            
            
            $list = db('ec_user')->alias('u')
                    ->field('b.people,b.success_people,b.shoudong_fenpei_people,b.assign_status,u.name,u.mobile,u.id,u.is_shangban,u.deptId,u.kehu_count')
                    ->join('ec_assign_feiyu_kehu_detail b','u.id = b.user_id AND b.assign_id=' . $assign_id,'left')                   
                    ->where($where_map)
                    ->where('u.deletetime',0)
                    ->order($sort, $order)
                    ->paginate($limit)->each(function($item){
                        $deparment_name = '';
                        if(!empty($item['deptId'])){
                            $deparment_name = db('ec_department')->where('deptId',$item['deptId'])->value('deptName');
                        }
                        
                        $item['deptName'] = $deparment_name;
                        return $item;
                    });
                    
            


            $result = array("total" => $list->total(), "rows" => $list->items());

            return json($result);
        }   
        $depeartment_list = db('ec_department')->field('deptId id,parentDeptId pid,deptName name,"true" checked,"true" spread')->where('delettime',0)->select();
        $treeobj = Tree::instance();
        $treeobj->init($depeartment_list);
        $result = $treeobj->getTreeArray(0);
//        $departmentlist =[
//            [
//                'title'=>'A-1','id'=>1,'field'=>'name1','checked'=>true,'spread'=>true,
//                'children'=>[
//                     ['title'=>'A-3dfdsfsd','id'=>1,'field'=>'name1','checked'=>true,'spread'=>true,]
//                ]
//            ]
//        ];
        
        $this->assignconfig('ids',$ids); //水印
        $this->assignconfig('departmentlist', $result);
        return $this->view->fetch();
    }
    
    public function assignCountShishi(){
        
        $request_data = $this->request->param();     
        $where_map = Null;
        if(!empty($request_data['deptId'])){
            $where_map['deptId'] = array('in',$request_data['deptId']);               
        }
        
        $today_start_time = strtotime("today");
        $assign_id = db('ec_assign_feiyu_kehu')->where(['status'=>['<>',2]])->order('id desc')->value('id');
        if(empty($assign_id)){
            $result = array("people_count" => 0, "success_people_count" => 0);
            return json($result);
            exit;
        }
        
        $plan_people = db('ec_user')->alias('u')
                    ->field('SUM(people) people_count,SUM(success_people) success_people_count')
                    ->join('ec_assign_feiyu_kehu_detail b','u.id = b.user_id AND b.assign_id=' . $assign_id,'left')    
                    ->where('u.deletetime',0)
                    ->where($where_map)
                    ->find();
       
        $result = array("people_count" => $plan_people['people_count'], "success_people_count" => $plan_people['success_people_count'],);
        return json($result);
    }

    



    public function edit($ids = null)
    {
        
        
        if (false === $this->request->isPost()) {
            $this->view->assign('row', $row);
            return $this->view->fetch();
        }
        $params = $this->request->post('row/a');
        if (empty($params)) {
            $this->error(__('Parameter %s can not be empty', ''));
        }
        
        $result = false;
        Db::startTrans();
        try {
            $today_start_time = strtotime("today");
                
            $assign_id = db('ec_assign_feiyu_kehu')->where(['status'=>['<>',2]])->order('id desc')->value('id');
            if(!empty($ids) && !empty($assign_id)){
                
                
                $exist_info = db('ec_assign_feiyu_kehu_detail')->where(['user_id'=>$ids,'assign_id'=>$assign_id])->count();
                if(!empty($exist_info)){
                    $result = db('ec_assign_feiyu_kehu_detail')->where(['user_id'=>$ids,'assign_id'=>$assign_id])->update(['people'=>$params['people'],'updatetime'=>time()]);
                }else{
                    $result = db('ec_assign_feiyu_kehu_detail')->insertGetId(['assign_id'=>$assign_id,'people'=>$params['people'],'user_id'=>$ids,'createtime'=>time()]);
                }
                
                if($result !== false){
                    $count_ = db('ec_assign_feiyu_kehu_detail')->where('assign_id',$assign_id)->sum('people');
                    db('ec_assign_feiyu_kehu')->where('id',$assign_id)->setField('count',$count_);
                }
                    
                
                
                
            }
            //是否采用模型验证
            
//            $result = $row->allowField(true)->save($params);
            Db::commit();
        } catch (Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if (false === $result) {
            $this->error(__('No rows were updated'));
        }
        $this->success();
    }
    
    
    public function batchUpdatePlan(){
        if (false === $this->request->isPost()) {
            $this->view->assign('row', $row);
            return $this->view->fetch();
        }
        $params = $this->request->post();
        if (empty($params)) {
            $this->error(__('Parameter %s can not be empty', ''));
        }
        
        $result = false;
        Db::startTrans();
        try {
            $people = $params['people'];
            $today_start_time = strtotime("today");
                
            $assign_id = db('ec_assign_feiyu_kehu')->where(['status'=>['<>',2]])->order('id desc')->value('id');
            if(!empty($assign_id)){
                $result = true;
                
                foreach ($params['list'] as $value){
                    $exist_info = db('ec_assign_feiyu_kehu_detail')->where(['user_id'=>$value['id'],'assign_id'=>$assign_id])->count();
                    if(!empty($exist_info)){
                        db('ec_assign_feiyu_kehu_detail')->where(['user_id'=>$value['id'],'assign_id'=>$assign_id])->update(['people'=>$people,'updatetime'=>time()]);
                    }else{
                        db('ec_assign_feiyu_kehu_detail')->insertGetId(['assign_id'=>$assign_id,'people'=>$people,'user_id'=>$value['id'],'createtime'=>time()]);
                    }
                }
                
                
                $count_ = db('ec_assign_feiyu_kehu_detail')->where('assign_id',$assign_id)->sum('people');
                db('ec_assign_feiyu_kehu')->where('id',$assign_id)->setField('count',$count_);
                
                    
                
                
                
            }
            //是否采用模型验证
            
//            $result = $row->allowField(true)->save($params);
            Db::commit();
        } catch (Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if (false === $result) {
            $this->error(__('No rows were updated'));
        }
        $this->success();
    }
    
    
    
    public function batchUpdateStatus(){
        if (false === $this->request->isPost()) {
            $this->view->assign('row', $row);
            return $this->view->fetch();
        }
        $params = $this->request->post();
        if (empty($params)) {
            $this->error(__('Parameter %s can not be empty', ''));
        }
        
        $result = false;
        Db::startTrans();
        try {
            
            $is_shangban = $params['is_shangban'];
            
            foreach ($params['list'] as $value){
                $user_id[] = $value['id'];                
            }
            
            $result = db('ec_user')->where('id','in',$user_id)->setField('is_shangban',$is_shangban);

            
            //是否采用模型验证
            
//            $result = $row->allowField(true)->save($params);
            Db::commit();
        } catch (Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if (false === $result) {
            $this->error(__('No rows were updated'));
        }
        $this->success('操作成功');
    }

    



    /**
     * 批量更新
     *
     * @param $ids
     * @return void
     */
    public function multi($ids = null)
    {
        if (false === $this->request->isPost()) {
            $this->error(__('Invalid parameters'));
        }
        $ids = $ids ?: $this->request->post('ids');
        if (empty($ids)) {
            $this->error(__('Parameter %s can not be empty', 'ids'));
        }

        if (false === $this->request->has('params')) {
            $this->error(__('No rows were updated'));
        }
        parse_str($this->request->post('params'), $values);
        $result = false;
        $count = 0;
        Db::startTrans();
        try {
            $result = db('ec_user')->where('id',$ids)->update($values);
            
            Db::commit();
        } catch (Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if (false === $result) {
            $this->error(__('No rows were updated'));
        }
        
        $this->success();
        
    }

}
